package org.jeecg.modules.business.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.business.entity.BussContractReviewDes;
import org.jeecg.modules.business.entity.BussContractReviewDesFiles;
import org.jeecg.modules.business.service.IBussContractReviewDesFilesService;
import org.jeecg.modules.business.service.IBussContractReviewDesService;
import org.jeecg.modules.business.vo.BussContractReviewDesPage;

import org.jeecg.modules.erp.base.entity.ErpCustomer;
import org.jeecg.modules.erp.base.service.IErpCustomerService;
import org.jeecg.modules.erp.base.service.IErpCustomerTypeService;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.mapper.FlowMyBusinessMapper;
import org.jeecg.modules.flowable.apithird.business.service.impl.FlowMyBusinessServiceImpl;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 合同评审说明
 * @Author: jeecg-boot
 * @Date: 2024-05-24
 * @Version: V1.0
 */
@Api(tags = "合同评审说明")
@RestController
@RequestMapping("/business/bussContractReviewDes")
@Slf4j
public class BussContractReviewDesController {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IBussContractReviewDesService bussContractReviewDesService;
    @Autowired
    private IBussContractReviewDesFilesService bussContractReviewDesFilesService;
    @Autowired
    private IErpCustomerService erpCustomerService;
    @Autowired
    private IErpCustomerTypeService typeService;

    /**
     * 分页列表查询
     *
     * @param bussContractReviewDes
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "合同评审说明-分页列表查询")
    @ApiOperation(value = "合同评审说明-分页列表查询", notes = "合同评审说明-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BussContractReviewDes>> queryPageList(BussContractReviewDes bussContractReviewDes,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        bussContractReviewDes.setLogtime(null);
        QueryWrapper<BussContractReviewDes> queryWrapper = QueryGenerator.initQueryWrapper(bussContractReviewDes, req.getParameterMap());
        Page<BussContractReviewDes> page = new Page<BussContractReviewDes>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String, String[]> ParameterMap = new HashMap<String, String[]>(req.getParameterMap());
        String[] column = new String[]{""};
        if (ParameterMap != null && ParameterMap.containsKey("column")) {
            column[0] = ParameterMap.get("column")[0];
            column[0] = "t." + column[0];
            ParameterMap.replace("column", column);
            log.info("修改的排序规则>>列:" + ParameterMap.get("column")[0]);
        }
        queryWrapper.eq("user_id", sysUser.getId());
        IPage<BussContractReviewDes> pageList = bussContractReviewDesService.myPage(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param bussContractReviewDesPage
     * @return
     */
    @AutoLog(value = "合同评审说明-添加")
    @ApiOperation(value = "合同评审说明-添加", notes = "合同评审说明-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BussContractReviewDesPage bussContractReviewDesPage) {
        BussContractReviewDes bussContractReviewDes = new BussContractReviewDes();
        BeanUtils.copyProperties(bussContractReviewDesPage, bussContractReviewDes);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        bussContractReviewDes.setUserId(sysUser.getId());
        bussContractReviewDesService.saveMain(bussContractReviewDes, bussContractReviewDesPage.getBussContractReviewDesFilesList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param bussContractReviewDesPage
     * @return
     */
    @AutoLog(value = "合同评审说明-编辑")
    @ApiOperation(value = "合同评审说明-编辑", notes = "合同评审说明-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BussContractReviewDesPage bussContractReviewDesPage) {
        BussContractReviewDes bussContractReviewDes = new BussContractReviewDes();
        BeanUtils.copyProperties(bussContractReviewDesPage, bussContractReviewDes);
        BussContractReviewDes bussContractReviewDesEntity = bussContractReviewDesService.getById(bussContractReviewDes.getId());
        if (bussContractReviewDesEntity == null) {
            return Result.error("未找到对应数据");
        }
        bussContractReviewDesService.updateMain(bussContractReviewDes, bussContractReviewDesPage.getBussContractReviewDesFilesList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同评审说明-通过id删除")
    @ApiOperation(value = "合同评审说明-通过id删除", notes = "合同评审说明-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        bussContractReviewDesService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同评审说明-批量删除")
    @ApiOperation(value = "合同评审说明-批量删除", notes = "合同评审说明-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.bussContractReviewDesService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同评审说明-通过id查询")
    @ApiOperation(value = "合同评审说明-通过id查询", notes = "合同评审说明-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BussContractReviewDes> queryById(@RequestParam(name = "id", required = true) String id) {
        BussContractReviewDes bussContractReviewDes = bussContractReviewDesService.getById(id);
        if (bussContractReviewDes == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(bussContractReviewDes);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同评审说明关联文件通过主表ID查询")
    @ApiOperation(value = "合同评审说明关联文件主表ID查询", notes = "合同评审说明关联文件-通主表ID查询")
    @GetMapping(value = "/queryBussContractReviewDesFilesByMainId")
    public Result<List<BussContractReviewDesFiles>> queryBussContractReviewDesFilesListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<BussContractReviewDesFiles> bussContractReviewDesFilesList = bussContractReviewDesFilesService.selectByMainId(id);
        return Result.OK(bussContractReviewDesFilesList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param bussContractReviewDes
     */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussContractReviewDes bussContractReviewDes) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<BussContractReviewDes> queryWrapper = QueryGenerator.initQueryWrapper(bussContractReviewDes, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<BussContractReviewDes> bussContractReviewDesList = bussContractReviewDesService.list(queryWrapper);

        // Step.3 组装pageList
        List<BussContractReviewDesPage> pageList = new ArrayList<BussContractReviewDesPage>();
        for (BussContractReviewDes main : bussContractReviewDesList) {
            BussContractReviewDesPage vo = new BussContractReviewDesPage();
            BeanUtils.copyProperties(main, vo);
            List<BussContractReviewDesFiles> bussContractReviewDesFilesList = bussContractReviewDesFilesService.selectByMainId(main.getId());
            vo.setBussContractReviewDesFilesList(bussContractReviewDesFilesList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "合同评审说明列表");
        mv.addObject(NormalExcelConstants.CLASS, BussContractReviewDesPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("合同评审说明数据", "导出人:" + sysUser.getRealname(), "合同评审说明"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_review_des:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BussContractReviewDesPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussContractReviewDesPage.class, params);
                for (BussContractReviewDesPage page : list) {
                    BussContractReviewDes po = new BussContractReviewDes();
                    BeanUtils.copyProperties(page, po);
                    bussContractReviewDesService.saveMain(po, page.getBussContractReviewDesFilesList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    @Autowired
    private FlowMyBusinessMapper flowMyBusinessMapper;

    /**
     * 反审核
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同评审说明-反审核")
    @ApiOperation(value = "合同评审说明-反审核", notes = "合同评审说明-反审核")
    @GetMapping(value = "/reverseCheck")
    public Result<BussContractReviewDes> reverseCheck(@RequestParam(name = "id", required = true) String id) {
        BussContractReviewDes bussContractReviewDes = bussContractReviewDesService.getById(id);
        if (bussContractReviewDes == null) {
            return Result.error("未找到对应数据");
        }
        BussContractReviewDes copyDes = new BussContractReviewDes();
        BeanUtils.copyProperties(bussContractReviewDes, copyDes);
        List<BussContractReviewDesFiles> list = bussContractReviewDesFilesService.list(new LambdaQueryWrapper<BussContractReviewDesFiles>().eq(BussContractReviewDesFiles::getContractReivewDesId, copyDes.getId()));

        copyDes.setCreateTime(null);
        copyDes.setUpdateTime(null);
        copyDes.setUpdateBy(null);
        copyDes.setCreateBy(null);
        bussContractReviewDesService.save(copyDes);
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(f -> {
                f.setId(null);
                f.setCreateTime(null);
                f.setUpdateTime(null);
                f.setUpdateBy(null);
                f.setCreateBy(null);
            });
        }
        bussContractReviewDesFilesService.saveBatch(list);
        String dataId = copyDes.getId();
        BeanMap variables = new BeanMap(copyDes);
        FlowMyBusiness flowMyBusiness = flowMyBusinessMapper.selectOne(new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getDataId, id).last(" limit 1"));
        if (Objects.isNull(flowMyBusiness)) {
            return Result.error("该表单尚未发起审批,不可以发起反审核操作");
        }
        String actStatus = flowMyBusiness.getActStatus();
        if (!"审批通过".equals(actStatus)) {
            return Result.error("只有审批通过的表单可以发起反审核操作");
        }
        // 转换为 Map<String, Object>
        Map<String, Object> map = new HashMap<>();
        for (Object key : variables.keySet()) {
            map.put((String) key, variables.get(key));
        }
        map.put("dataId", dataId);
        return flowDefinitionService.startProcessInstanceByDataId(dataId, "contractReviewDesService", map);
    }

    @ApiOperation(value = "根据客户查询业务员", notes = "根据客户查询业务员")
    @GetMapping(value = "/querySalesman")
    public Result<Map> querySalesman(@RequestParam(name = "id", required = true) String id) {
        ErpCustomer customer = erpCustomerService.getById(id);
        String salesman = customer.getSalesman();
        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(salesman)) {
            SysUser sysUser = new SysUser();
            sysUser.setUsername(salesman);
            QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, null);
            //update-begin---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
            queryWrapper.eq("status", Integer.parseInt(CommonConstant.STATUS_1));
            //update-end---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
            List<SysUser> ls = sysUserMapper.selectList(queryWrapper);
            for (SysUser user : ls) {
                user.setPassword(null);
                user.setSalt(null);
            }
            String concatenatedNames = ls.stream()
                    .map(SysUser::getRealname) // 获取每个 SysUser 对象的 realname 属性
                    .collect(Collectors.joining(",")); // 将获取到的 realname 使用逗号连接起来

            map.put("salesman", concatenatedNames);
            map.put("type", typeService.getById(customer.getType()));
            return Result.ok(map);
        }
        return Result.OK(map);
    }
}
